package one.three.thirty;

public class Reverse {

	private static class Node<Item> {
		private Item item;
		private Node next;

		private Node<Item> reverse(Node<Item> n) {
			if (n != null && n.next != null) {
				Node<Item> c = n;
				Node<Item> r = null;
				Node<Item> t = null;
				while (c != null) {

					t = r;
					r = new Node<Item>();
					r.item = c.item;
					r.next = t;

					c = c.next;
				}
				return r;
			}
			return n;
		}

		private Node<Item> reverseRecursion(Node<Item> n) {
			if(n==null || n.next==null)
				return n;
			else {
				Node<Item> r=reverseRecursion(n.next);
				Node<Item> t=r;
				while(t.next!=null) {
					t=t.next;
				}
				t.next=new Node<Item>();
				t.next.item=n.item;
				return r;
			}
		}
		
		@Override
		public String toString() {
			return "[" + item + "]";
		}
	}

	public static void main(String[] args) {
		Node<Integer> f = new Node<Integer>();
		f.item = 0;
		Node<Integer> c = f;
		for (int i = 1; i <= 5; i++) {
			c.next = new Node<Integer>();
			c.next.item = i;
			c = c.next;
		}

		c = f;
		while (c != null) {
			System.out.println(c.item);
			c = c.next;
		}

		System.out.println("---");
		//Node<Integer> r = f.reverse(f);
		Node<Integer> r = f.reverseRecursion(f);
		c = r;
		while (c != null) {
			System.out.println(c.item);
			c = c.next;
		}
	}

}
